package kr.co.cherryt.receiver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import kr.co.cherryt.activity.CherryTActivity;
import kr.co.cherryt.cherryt.R;
import kr.co.cherryt.cherryt.R.drawable;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.widget.Toast;

public class C2dmReceiver extends BroadcastReceiver {
	static String registration_id = null;
	static String c2dm_msg = "";
	static int NOTIFICATION_ID = 0;

	@Override
	public void onReceive(Context context, Intent intent) {
		//Log.d("cherryt", "push intent" );
		if( intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
			String strRegistrationId = intent.getStringExtra("registration_id");

			CherryTActivity.strRegistrationID = strRegistrationId;

			sendRegistrationIdToServer(CherryTActivity.userInfo.getUserID(), strRegistrationId);
			saveRegistrationId(context, strRegistrationId);

			//Log.d("cherryt", "push id: " + strRegistrationId );
		}

		// 푸쉬 수신 메시지
		if( intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
			//php에서 푸쉬 전송내용 가져오기
			c2dm_msg = intent.getStringExtra("msg");
			//전송내용 출력하기
			Toast toast = Toast.makeText(context, c2dm_msg, Toast.LENGTH_LONG);
			toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
			toast.show();
			//알림으로 등록
			final String payload = intent.getStringExtra("payload");
			createNotification( context, payload );
		}
	}

	private void saveRegistrationId(Context context, String registrationId) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		Editor edit = prefs.edit();
		edit.putString("AuthRID", registrationId);
		edit.commit();
	}

	public void sendRegistrationIdToServer(String email, String registrationId) {
		//Log.d("cherryt", "registration ID");
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://cherryt.co.kr/ct/registerc2dmid.php");
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

			nameValuePairs.add(new BasicNameValuePair("email", email));
			nameValuePairs.add(new BasicNameValuePair("id",
					registrationId));

			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = "";
			while ((line = rd.readLine()) != null) {
				//Log.d("cherryt", "pppppppppush id: " + email);
				//Log.d("HttpResponse", line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void createNotification(Context context, String msg) {
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.icon,
				"체리티 알림", System.currentTimeMillis());
		// Hide the notification after its selected
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		Intent intent = new Intent(context, CherryTActivity.class);
		intent.putExtra("payload", msg);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
		notification.defaults |= (Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);    
		notification.setLatestEventInfo(context, "체리티",
				c2dm_msg, pendingIntent);
		NOTIFICATION_ID++;
		notification.number = NOTIFICATION_ID;
		notificationManager.notify(1, notification);
	}

	public static String getToken(String email, String password)
			throws IOException {
		// Create the post data
		// Requires a field with the email and the password
		StringBuilder builder = new StringBuilder();
		builder.append("Email=").append(email);
		builder.append("&Passwd=").append(password);
		builder.append("&accountType=GOOGLE");
		builder.append("&source=MyLittleExample");
		builder.append("&service=ac2dm");

		// Setup the Http Post
		byte[] data = builder.toString().getBytes();
		URL url = new URL("https://www.google.com/accounts/ClientLogin");
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setUseCaches(false);
		con.setDoOutput(true);
		con.setRequestMethod("POST");
		con.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		con.setRequestProperty("Content-Length", Integer.toString(data.length));

		// Issue the HTTP POST request
		OutputStream output = con.getOutputStream();
		output.write(data);
		output.close();

		// Read the response
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				con.getInputStream()));
		String line = null;
		String auth_key = null;
		while ((line = reader.readLine()) != null) {
			if (line.startsWith("Auth=")) {
				auth_key = line.substring(5);
			}
		}

		// Finally get the authentication token
		// To something useful with it
		return auth_key;
	}
}
